<template>
  <div class="page-main">
    <div class="cn-title">
      {{ titleTxt[actionType] }}
    </div>
    <div class="cn-cont">
      <div class="form-wrap">
        <el-form
          :model="loginForm"
          label-width="80px"
          label-position="top"
          :rules="formRules"
          ref="loginFormRef"
        >
          <el-form-item label="手机号：" prop="phone">
            <el-input
              v-model.trim="loginForm.phone" placeholder="请输入手机号" size="large"
            />
          </el-form-item>

          <el-form-item label="原密码：" prop="oldPassword" v-if="actionType === 'update'" :rules="[{ required: true, message: '原密码不能为空', trigger: 'blur'}]">
            <el-input
              v-model.trim="loginForm.oldPassword" placeholder="请输入原密码" size="large"
              type="password"
            />
          </el-form-item>
          
          <el-form-item label="密码：" prop="password">
            <el-input
              v-model.trim="loginForm.password"
              placeholder="请输入密码"
              size="large"
              type="password"
            />
          </el-form-item>
          <el-form-item
            label="确认密码:"
            prop="rePassword"
            v-if="actionType === 'update'"
            :rules="[
              { required: true, message: '确认密码不能为空', trigger: 'blur' },
              { validator: validatePass2, trigger: 'blur' }
            ]"
          >
            <el-input
              v-model.trim="loginForm.rePassword"
              placeholder="请再次输入手机号"
              size="large"
              type="password"
            />
          </el-form-item>
          <el-form-item label="验证码:" prop="inputVcode">
            <div class="guiCode-wrap">
              <el-input
                v-model.trim="loginForm.inputVcode"
                placeholder="请输入验证码"
                size="large"
              />
              <identifyCodeCom
                :identifyCode="identifyCode"
                @click="refreshIdentifyCode"
              ></identifyCodeCom>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button class="submit-btn" type="primary" @click="submitForm(loginFormRef)" size="large">{{
              actionBtnTxt[actionType]
            }}</el-button>
          </el-form-item>
          <el-form-item>
            <div class="link-btn">
              <div class="lb-left">
                <el-button link @click="convertToUpdate">修改密码?</el-button>
                <el-button link @click="forgetPasswordFn">忘记密码?</el-button>
              </div>
              <div class="lb-right">
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted ,watch,onUpdated} from 'vue'
// 登录弹窗
import identifyCodeCom from '@/components/identifyCode'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/api/fetch'
import { loadStore } from '@/store'
import { useRouter, useRoute } from 'vue-router';
const userStore = loadStore()
const router = useRouter()
const route = useRoute()


// const { setting,orderNo } = userStore


const loginFormRef = ref(null)
// 操作分为登录login，register,update更改密码
const actionType = ref('login')



watch(route,(newVal)=>{
    if(['login','update'].includes(route.query.actionType)){
      actionType.value = route.query.actionType
    }else {
      actionType.value = 'login'
    }
    
},{immediate: true,deep: true})

const actionBtnTxt = reactive({
  login: '登录',
  update: '更新密码'
})
const loginForm = reactive({
  phone: '',
  code: '',
  oldPassword:'',
  password: '',
  rePassword: '',
  inputVcode: ''
})
// 验证码
const identifyCode = ref('')

const titleTxt = reactive({
  login: '登录',
  update: '更新密码'
})
const reqLoading = ref(false)

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (loginForm.rePassword !== '') {
      if (!loginFormRef.value) return
      loginFormRef.value.validateField('rePassword', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== loginForm.password) {
    callback(new Error('两次密码必须相同'))
  } else {
    callback()
  }
}

const validateVcode = (rule, value, callback) => {
  if (identifyCode.value.toLowerCase() !== value.toLowerCase()) {
    callback(new Error('验证码错误'))
  } else {
    callback()
  }
}

const commonRules = {
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern:
      /^(0|86|17951)?(13[0-9]|15[012356789]|16[0-9]|17[0-9]|18[0-9]|19[0-9]|14[57])[0-9]{8}$/,
      message: '手机号格式错误',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  inputVcode: [
  { required: true, message: '验证码不能为空', trigger: 'change' },
    { validator: validateVcode, trigger: 'change' }]
}
const loginRules = {
  ...commonRules,
}
const updateRules = {
  ...commonRules,
}


let  formRules = ref(loginRules)

watch(actionType,(newValue)=>{
  if(newValue ==='login'){
    formRules.value = loginRules
  }else {
    formRules.value = updateRules
  }
  setTimeout(()=>{
    if(loginFormRef.value){
      loginFormRef.value.clearValidate()
    }
  },0)
})


function loginRegisterSuccess(res){
  if(res){
    userStore.setToken(res.token)
    userStore.setUserInfo(res.user)
    
    ElMessage({
      type:'success',
      message: actionBtnTxt[actionType.value]+'成功'
    })
    setTimeout(()=>{
      router.push({path:'/'})
    },0)
  }
  reqLoading.value = false
}

async function loginFn(queryObj){
  reqLoading.value = true
  let res = await request('/login',{
    method:'POST',
    body:queryObj
  })
  loginRegisterSuccess(res)
}
async function updatePassword(queryObj){
  reqLoading.value = true
  let res = await request('/updateUserPassword',{
    method:'POST',
    body:queryObj
  })

  ElMessage({
    type:'success',
    message: '更新成功,请重新登录'
  })
  userStore.loginOut()
  resetForm()
  actionType.value='login'
  setTimeout(()=>{
    router.push({path:'/login',query:{actionType:'login'}})
  },0)
  
  console.log('updatePassword res:',res)
}
function submitForm(formEl) {
  // 提交表单
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      let queryObj = {
          phone:loginForm.phone,
          password:loginForm.password
        }
      if(actionType.value === 'login'){
        loginFn(queryObj)
      }else if(actionType.value === 'update'){
        queryObj.oldPassword = loginForm.oldPassword
        updatePassword(queryObj)
      }
    } else {
      console.log('error submit!')
      return false
    }
    refreshIdentifyCode()
  })
  
}

function resetForm() {
  if (!loginFormRef.value) return
  loginFormRef.value.resetFields()
  setTimeout(()=>{
    refreshIdentifyCode()
    loginFormRef.value.clearValidate()
  },0)
  
}

function makeIdentifyCode(l) {
  let identifyKey = '234567890abcdefghzklmnopqrstuvwxyzABCDEFGHZKLMNOPQRSTUVWXYZ'
  for (let i = 0; i < l; i++) {
    identifyCode.value += identifyKey[randomNum(0, identifyKey.length)]
  }
}
// 生成单个验证码
function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min)
}

function refreshIdentifyCode() {
  identifyCode.value = ''
  makeIdentifyCode(4)
}


function convertToUpdate(){
  resetForm()
  actionType.value = 'update'
}

function forgetPasswordFn(){
  ElMessageBox.alert('请提供手机号给管理员v：guo330504','提示',{

  }).catch(()=>{

  })
}


onMounted(() => {
  makeIdentifyCode(4)
  
})


</script>
<style scoped lang="scss">
.page-main {
  min-height: calc(100vh - 120px);
  .cn-title {
    text-align: center;
    padding: 20px;
    box-sizing: border-box;
    font-size: 24px;
    font-weight: bold;
    height: 60px;
  }
  .cn-cont {
    margin: 0 auto;
    box-sizing: border-box;
    max-width: 1200px;
    margin: auto;
    padding: 20px 20px;
    background: white;
    min-height: calc(100vh - 120px);
    padding-bottom: 20px;
    .cn-vip{
      text-align: center;
      font-weight: bold;
      background: linear-gradient(90deg, red, blue);
      -webkit-text-fill-color: transparent;
      -webkit-background-clip: text;
    }
    .form-wrap {
      margin: auto;
      max-width: 320px;
      margin-top: 20px;
      .el-form-item {
        margin-bottom: 18px;
      }
    }
  }
  .guiCode-wrap {
    display: flex;
    align-items: center;
    .guiCode {
      width: 64px;
      height: 64px;
    }
  }
  .submit-btn{
    width: 100%;
  }
  .link-btn{
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .el-button{
      &:hover{
        text-decoration: underline;
      }
      
    }
  }
}
</style>
